package com.wuhuiyue.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.wuhuiyue.entity.Group;
import com.wuhuiyue.entity.Seartch;
import com.wuhuiyue.entity.Software;
import com.wuhuiyue.entity.Softwarevo;
import com.wuhuiyue.service.ISoftwareService;
import com.wuhuiyue.service.ISoftwarevoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author hy woo
 * @date 2022/6/11 13:44
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    ISoftwareService softwareService;
    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("软件管理", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Software> list = softwareService.list();
        EasyExcel.write(response.getOutputStream(), Software.class).sheet("软件管理").doWrite(list);
    }

    @GetMapping("download2")
    public void download2(HttpServletResponse response,@RequestBody Seartch seartch) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("分组管理", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        seartch.setDatea(DateUtil.parse("1912-12-1"));
        seartch.setDateb(DateUtil.parse("2100-1-3"));
        List<Group> groupList=softwareService.countByGid(seartch.getDatea(),seartch.getDateb());
        EasyExcel.write(response.getOutputStream(), Group.class).sheet("分组管理").doWrite(groupList);
    }
}
